package com.rd.config;

import com.rd.config.security.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

import javax.annotation.Resource;

/**
 * 权限配置文件
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] PASSLIST={"/login","/logout","/images/**","/test/**"};

    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private LoginFailureHandler loginFailureHandler;
    @Resource
    private MyUserDetailServiceImpl myUserDetailService;
    @Resource
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Resource
    private MyLogoutSuccessHandler myLogoutSuccessHandler;


    //注册@Bean注册过滤器
    @Bean
    JwtAuthenticationFilter createJwFilter() throws Exception{
        return new JwtAuthenticationFilter(authenticationManager());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 正在配置一个AuthenticationManager 认证管理器
        auth.userDetailsService(myUserDetailService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //前端是vue项目,开启跨域--关闭csrf防护
        http.cors().and().csrf().disable()
        //使用token认证方式,不需要保存session值,禁用session
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        //开启表单验证
        .formLogin()
        //登录处理的url
        .loginProcessingUrl("/login")
        //如果前端传递的表单的name属性不是默认 username或者password
        .usernameParameter("username")
        .passwordParameter("password")
        //配置登录成功处理器和失败处理器
        .successHandler(loginSuccessHandler)
        .failureHandler(loginFailureHandler)
        //成功退出
        .and().logout().logoutSuccessHandler(myLogoutSuccessHandler)
        //配置访问规则
        .and().authorizeRequests()
        //设置放行路径
        .antMatchers(PASSLIST).permitAll()
        //其他所有的请求都需要用户认证菜可以访问
        .anyRequest().authenticated()
        //认证失败入口点---处理器
        .and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
        //自定义过滤器配置
        .and().addFilter(createJwFilter());
    }
}
